/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.web.action.debt;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.academy.service.CourseService;
import ar.uba.fi.posgrado.common.model.Student;
import ar.uba.fi.posgrado.common.util.CommonUtils;
import ar.uba.fi.posgrado.economy.model.Benefit;
import ar.uba.fi.posgrado.economy.model.Customer;
import ar.uba.fi.posgrado.economy.model.Debt;
import ar.uba.fi.posgrado.economy.model.Discount;
import ar.uba.fi.posgrado.economy.service.DebtService;
import ar.uba.fi.posgrado.economy.web.form.debt.DebtForm;
import ar.uba.fi.posgrado.economy.web.util.CourseToLabelValueTransformer;
import ar.uba.fi.posgrado.economy.web.util.DebtTypeToLabelValueTransformer;

/**
 * Action que muestra una deuda en particular.<br>
 * 
 * @author nicolas.gonzalez
 * @see Action
 */
public class ShowDebtAction extends Action {

    /** Logger */
    private static Logger logger = Logger.getLogger(ShowDebtAction.class);
    
    private DebtService debtService;
    private CourseService courseService;

    // IoC
    public void setDebtService(DebtService debtService) {
        this.debtService = debtService;
    }
    // IoC
	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}


	/**
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @SuppressWarnings("unchecked")
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("Por mostrar pantalla de modificacion de deuda ...");
        }
        DebtForm form = (DebtForm)actionForm;
        Long debtId = form.getId();
        Debt debt = this.debtService.getById(debtId);
        Student student = debt.getStudent();
        Customer customer = debt.getCustomer();
        Course course = debt.getCourse();
        
        Set<Discount> discounts = debt.getDiscounts();
        Set<Benefit> benefits = debt.getBenefits();
        
        form.setDiscountValues(this.calculateDiscount(discounts, "value"));
        form.setDiscountPerc(this.calculateDiscount(discounts, "percentage"));
        form.setBenefitValues(this.calculateBenefit(benefits, "value"));
        form.setBenefitPerc(this.calculateBenefit(benefits, "percentage"));
        form.setSelectedDiscounts(this.discountIdsAsString(discounts));
        form.setSelectedBenefits(this.benefitIdsAsString(benefits));
        // Tipo de concepto de la deuda.
        form.setDebtTypeSelected(String.valueOf(debt.getDebtType().getId()));
        // Datos del usuario
        form.setStudentId(student.getId());
        form.setStudentSurname(student.getSurnamePlusName());
        // Datos del cliente
        form.setCustomerId(customer.getId());
    	form.setCorporateName(customer.getCorporateName());
    	// Curso
    	form.setCourseSelected(String.valueOf((course.getId())));
    	
        // Fechas
        form.setValidityFrom(CommonUtils.formatDate(debt.getValidityFrom()));
        form.setExpiry(CommonUtils.formatDate(debt.getExpiry()));
        form.setBalance(debt.getBalance());
        form.setOriginalBalance(debt.getOriginalBalance());
        
        // Carga los tipos de deuda disponibles
        List debtTypes = this.debtService.getAllDebtTypes();
        // Aca se cambia el tipo de la collection, por eso no esta tipada
        CollectionUtils.transform(debtTypes, new DebtTypeToLabelValueTransformer());
        form.setDebtTypeOptions(debtTypes);
        
        List courses = this.courseService.getAll();
        if (logger.isDebugEnabled()) {
            logger.debug("Cursos a mostrar: " + courses.size());
        }
        CollectionUtils.transform(courses, new CourseToLabelValueTransformer());
        form.setCourseOptions(courses);
        
        logger.info("Mostrar pantalla de modificacion de deuda finalizado");
        return mapping.findForward("success");
    }

    
    /**
     * Calcula el acumulado de descuentos tanto por valor como
     * por porcentaje.<br>
     * 
     * @param discounts
     * @param valueOrPerc "value"|"percentage"
     * @return
     */
    private String calculateDiscount(Set<Discount> discounts, String valueOrPerc) {
        String response = "";

        Double aux = 0d;
        if (valueOrPerc.equals("value")) {
            for (Discount discount : discounts) {
                aux += discount.getValue();
            }
        }
        else {
            for (Discount discount : discounts) {
                aux += discount.getPercentage();
            }
        }
        response = String.valueOf(aux);
        
        return response;
    }

    /**
     * Calcula el acumulado de beneficios tanto por valor como
     * por porcentaje.<br>
     * 
     * @param benefits beneficios
     * @param valueOrPerc "value"|"percentage"
     * @return
     */
    private String calculateBenefit(Set<Benefit> benefits, String valueOrPerc) {
        String response = "";

        Double aux = 0d;
        if (valueOrPerc.equals("value")) {
            for (Benefit benefit: benefits) {
                aux += benefit.getValue();
            }
        }
        else {
            for (Benefit benefit: benefits) {
                aux += benefit.getPercentage();
            }
        }
        response = String.valueOf(aux);
        
        return response;
    }

    /**
     * Pone los Ids de los benefits en un String separado por ';'
     * @param benefits
     * @return
     */
    private String benefitIdsAsString(Set<Benefit> benefits) {
        StringBuffer response = new StringBuffer("");
        
        for (Benefit benefit: benefits) {
            if (StringUtils.isNotEmpty(response.toString())) {
                response.append(";");
            }
            
            response.append(benefit.getId());
        }
        
        return response.toString();
    }

    /**
     * Pone los Ids de los benefits en un String separado por ';'
     * @param benefits
     * @return
     */
    private String discountIdsAsString(Set<Discount> discounts) {
        StringBuffer response = new StringBuffer("");
        
        for (Discount discount: discounts) {
            if (StringUtils.isNotEmpty(response.toString())) {
                response.append(";");
            }
            
            response.append(discount.getId());
        }
        
        return response.toString();
    }
    
}
